<template>
  <div class="code-highlight-container">
    <div class="code-header">
      <span class="language-label">{{ language }}</span>
      <el-button 
        size="small" 
        type="primary" 
        icon="Copy" 
        @click="copyCode"
        class="copy-btn"
      >
        复制
      </el-button>
    </div>
    <pre><code :class="`language-${language}`" ref="codeRef" v-html="highlightedCode"></code></pre>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import hljs from 'highlight.js/lib/core'
import java from 'highlight.js/lib/languages/java'
import sql from 'highlight.js/lib/languages/sql'
import xml from 'highlight.js/lib/languages/xml'
import 'highlight.js/styles/github.css'

// 注册语言
hljs.registerLanguage('java', java)
hljs.registerLanguage('sql', sql)
hljs.registerLanguage('xml', xml)

interface Props {
  code: string
  language?: string
}

const props = withDefaults(defineProps<Props>(), {
  language: 'java'
})

const codeRef = ref<HTMLElement>()

const highlightedCode = computed(() => {
  if (!props.code) return ''
  try {
    return hljs.highlight(props.code, { language: props.language }).value
  } catch (error) {
    console.warn('代码高亮失败:', error)
    return props.code
  }
})

const copyCode = async () => {
  try {
    await navigator.clipboard.writeText(props.code)
    ElMessage.success('代码已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

watch(() => props.code, () => {
  if (codeRef.value) {
    hljs.highlightElement(codeRef.value)
  }
})

onMounted(() => {
  if (codeRef.value) {
    hljs.highlightElement(codeRef.value)
  }
})
</script>

<style scoped>
.code-highlight-container {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  background-color: #fafafa;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.language-label {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
  text-transform: uppercase;
}

.copy-btn {
  padding: 4px 8px;
  font-size: 12px;
}

pre {
  margin: 0;
  padding: 16px;
  background-color: #fafafa;
  overflow-x: auto;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
}

code {
  background: none;
  padding: 0;
  font-family: inherit;
  font-size: inherit;
}

/* 自定义滚动条 */
pre::-webkit-scrollbar {
  height: 8px;
}

pre::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

pre::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

pre::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>